package com.ycsj.goldmedalnewconcept.activity;
import android.annotation.SuppressLint;
import android.app.ActivityManager;
import android.app.ActivityManager.RunningAppProcessInfo;
import android.app.ActivityManager.RunningTaskInfo;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.util.Log;

import com.google.gson.Gson;
import com.squareup.okhttp.Call;
import com.squareup.okhttp.Callback;
import com.squareup.okhttp.OkHttpClient;
import com.squareup.okhttp.Request;
import com.squareup.okhttp.Response;
import com.ycsj.goldmedalnewconcept.bean.HomeWorkRespons;
import com.ycsj.goldmedalnewconcept.bean.timeresq;
import com.ycsj.goldmedalnewconcept.constant.ConfigConstant;
import com.ycsj.goldmedalnewconcept.constant.NetConstant;
import com.ycsj.goldmedalnewconcept.utils.SPUtils;

import java.io.IOException;
import java.util.List;

//import com.umeng.analytics.MobclickAgent;
   
/** 
 * 名称：BaseActivity  
 * 描述：  
 * 创建人：  
 * 日期：2016-6-23 上午9:53:35  
 * 变更： 
 */  
   
@SuppressLint("NewApi")
public class BaseJpStarActivity extends FragmentActivity {
	

		@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		
		// 注册事件  
        registerReceiver(myReceiver, new IntentFilter(Intent.ACTION_SCREEN_ON));  
        registerReceiver(myReceiver, new IntentFilter(Intent.ACTION_SCREEN_OFF));  
        registerReceiver(myReceiver, new IntentFilter(Intent.ACTION_USER_PRESENT)); 
		
	}

		@SuppressWarnings({ "deprecation", "unused" })
		@Override  
        protected void onStop() {  
                // TODO Auto-generated method stub  
                super.onStop();  
                ActivityManager manager = (ActivityManager) getSystemService (ACTIVITY_SERVICE);
            	List<RunningTaskInfo> task_info = manager.getRunningTasks(20);
            	String packageName = task_info.get(0).topActivity.getPackageName();
            	Log.e("test", "onStop+onStop=onStop");
                if(!"com.ycsj.management".equals(packageName)){
            	
                	SPUtils.put(BaseJpStarActivity.this, ConfigConstant.ISAPPONFOREGROUND, false);
                	Log.e("test", "onStop+onStop=onStoponStoponStop");
            		OkHttpClient mOkHttpClient = new OkHttpClient();
            		// 创建一个Request
            		final Request request = new Request.Builder().url(NetConstant.USERONLINE+ "SaveUserOnlineEnd.aspx?rid="+SPUtils.getString(BaseJpStarActivity.this, ConfigConstant.RID)
            				+"&account="+ SPUtils.getString(this,ConfigConstant.USERNAME)).build();
            		// new call
            		Call call = mOkHttpClient.newCall(request);
            		call.enqueue(callBackSystemTimefinish);
            		
//            		Log.e("test", NetConstant.USERONLINE+ "SaveUserOnlineEnd.aspx?rid="+
//            										SPUtils.getString(BaseActivity.this, ConfigConstant.RID)
//            										+"&account="
//    						+ SPUtils.getString(this,ConfigConstant.USERNAME));
                	
        		}
               
        }  
   
        @Override  
        protected void onResume() {  
                // TODO Auto-generated method stub  
                super.onResume();  
            	
//                MobclickAgent.onResume(this);
                if (isAppOnForeground()) {  
//                        //app 从后台唤醒，进入前台  
//                           Toast.makeText(BaseActivity.this, "进入前台 ", 0).show();
//                           
//                	Log.e("test", "onResume+onResume=onResume");
                	if(!SPUtils.getBoolean(BaseJpStarActivity.this, ConfigConstant.ISAPPONFOREGROUND)){
                		Log.e("test", "ConfigConstant.ISAPPONFOREGROUND=false");
                		SPUtils.put(BaseJpStarActivity.this, ConfigConstant.ISAPPONFOREGROUND, true);
            			OkHttpClient mOkHttpClient = new OkHttpClient();
                		// 创建一个Request
                		final Request request = new Request.Builder().url(NetConstant.USERONLINE+ "InitUserOnlineBegin.aspx?account="
    							+ SPUtils.getString(BaseJpStarActivity.this,ConfigConstant.USERNAME)+"-android"
								).build();
                		// new call
                		Call call = mOkHttpClient.newCall(request);
                		call.enqueue(callBackSystemTime);
                	}
                }  
        }  
   
        /** 
         * 程序是否在前台运行 
         *  
         * @return 
         */  
        public boolean isAppOnForeground() {  
                // Returns a list of application processes that are running on the  
                // device  
                   
                ActivityManager activityManager = (ActivityManager) getApplicationContext().getSystemService(Context.ACTIVITY_SERVICE);  
                String packageName = getApplicationContext().getPackageName();  
//                Log.e("word", packageName);
                List<RunningAppProcessInfo> appProcesses = activityManager  
                                .getRunningAppProcesses();  
                if (appProcesses == null)  
                        return false;  
   
                for (RunningAppProcessInfo appProcess : appProcesses) {  
                        // The name of the process that this object is associated with.  
                        if (appProcess.processName.equals(packageName) 
                                        && appProcess.importance == RunningAppProcessInfo.IMPORTANCE_FOREGROUND) {  
                          
                        	
                        	return true;  
                        }  
                }  
   
                return false;  
        }  
        
        
        
Callback callBackSystemTimefinish=new Callback() {
	
	@Override
	public void onResponse(Response arg0) throws IOException {
		// TODO Auto-generated method stub
		
	}
	
	@Override
	public void onFailure(Request arg0, IOException arg1) {
		// TODO Auto-generated method stub
		
	}
};


	  	
	  	
	  	private String rid;
		 Callback callBackSystemTime=new Callback() {
			
			@Override
			public void onResponse(Response arg0) throws IOException {
	  			// TODO Auto-generated method stub
	  			String json = arg0.body().string();
	  			// 使用Gson把json解析成对象
	  			// 1 得到gson对象

//	  			Log.i("testtime", json.toString());

	  			Gson gson = new Gson();
	  			timeresq fromJson = gson.fromJson(json, timeresq.class);
	  			rid = fromJson.rid;
	  			SPUtils.put(BaseJpStarActivity.this, ConfigConstant.RID, rid);
	  			HomeWorkRespons mHomeWorkRespons = gson.fromJson(json, HomeWorkRespons.class);
	  			SPUtils.put(getApplicationContext(), "haveHomeWork", mHomeWorkRespons.testflag);
	  			Log.i("testtime", "ddfs"+SPUtils.getString(getApplicationContext(), "haveHomeWork"));
	  		}
			
			@Override
			public void onFailure(Request arg0, IOException arg1) {
				// TODO Auto-generated method stub
				
			}
		}; 


	
		  	
		  	protected  boolean isTopActivity(){
		        String className = "com.ycsj.management.WordsYuxiActivity";
		        ActivityManager activityManager =  (ActivityManager) getApplicationContext().getSystemService(Context.ACTIVITY_SERVICE);
		        List<RunningTaskInfo>  tasksInfo = activityManager.getRunningTasks(1);  
		        if(tasksInfo.size() > 0){  
		            System.out.println("---------------包名-----------"+tasksInfo.get(0).topActivity.getPackageName());
		            //应用程序位于堆栈的顶层  
//		            Log.d("word", tasksInfo.get(0).topActivity.getClassName());
		            if(className.equals(tasksInfo.get(0).topActivity.getClassName())){ 
		            	
		                return true;  
		            }  
		        }  
		        return false;
		    }

			@Override
			protected void onPause() {
				// TODO Auto-generated method stub
				super.onPause();
//				MobclickAgent.onPause(this);
			}
		  	
		  
			private BroadcastReceiver myReceiver = new BroadcastReceiver() {  
		          
		        @Override  
		        public void onReceive(Context context, Intent intent) {  
		            // TODO Auto-generated method stub  
		            if (Intent.ACTION_SCREEN_ON.equals(intent.getAction()) ) {//当按下电源键，屏幕亮起的时候  
		                  
		            }  
		            if (Intent.ACTION_SCREEN_OFF.equals(intent.getAction()) ) {//当按下电源键，屏幕变黑的时候  
//		                islockScreen = true;  
		            	Log.e("test", "屏幕变黑");
		            	 ActivityManager manager = (ActivityManager) getSystemService (ACTIVITY_SERVICE);
		             	List<RunningTaskInfo> task_info = manager.getRunningTasks(20);
		             	String packageName = task_info.get(0).topActivity.getPackageName();
		             	Log.e("test", "onStop+onStop=onStop");
		             	
		                 	SPUtils.put(BaseJpStarActivity.this, ConfigConstant.ISAPPONFOREGROUND, false);
		                 	Log.e("test", "onStop+onStop=屏幕变黑onStoponStoponStop");
		             		OkHttpClient mOkHttpClient = new OkHttpClient();
	                		// 创建一个Request
	                		final Request request = new Request.Builder().url(NetConstant.USERONLINE+ "SaveUserOnlineEnd.aspx?rid="+SPUtils.getString(BaseJpStarActivity.this, ConfigConstant.RID)
		             				+"&account="+ SPUtils.getString(BaseJpStarActivity.this,ConfigConstant.USERNAME)
										).build();
	                		// new call
	                		Call call = mOkHttpClient.newCall(request);
	                		call.enqueue(callBackSystemTimefinish);
		            }  
		            if (Intent.ACTION_USER_PRESENT.equals(intent.getAction()) ) {//当解除锁屏的时候  
//		                islockScreen = false;  
		            }  
		        }  
		    };

			@Override
			protected void onDestroy() {
				// TODO Auto-generated method stub
				super.onDestroy();
				try {  
				    unregisterReceiver(myReceiver);  
				} catch (IllegalArgumentException e) {  
				    if (e.getMessage().contains("Receiver not registered")) {  
				        // Ignore this exception. This is exactly what is desired  
				    } else {  
				        // unexpected, re-throw  
				        throw e;  
				    }  
				} 
			}  	
		  	
		    
		    
}  